package com.pomr.service.common.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.pomr.model.equipmentstorage.EquipmentLeader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.pomr.dao.equipmentreceive.ReceiveDao;
import com.pomr.model.data.AalData;
import com.pomr.model.equipmentstorage.MonitoringData;
import com.pomr.model.equipmentstorage.Receive;
import com.pomr.service.aop.ControllerLogService;
import com.pomr.service.common.AalDataService;
@Service
public class AalDataServiceImpl implements AalDataService {
	private static Logger log = LoggerFactory.getLogger(AalDataServiceImpl.class);
	@Autowired
	@Qualifier("receiveDaoImpl")
	private ReceiveDao receiveDao;
	
	@Transactional(rollbackFor=Exception.class)
	public boolean uploadData(AalData ad) throws Exception{
		MonitoringData md = ad.findMonitor();
//		ad.setSerialnumber("");
		//获取设备领取信息
		String hql = "from EquipmentLeader where nouseTime = null and receive.match.equipmentdetail.sN = '"+ad.getSerialnumber()+"' ";
		if(ad.getUser()==null || ad.getUser().equals("")){
			hql += "and userNo='1'";
		}else if(ad.getUser().equals("0")){
			hql += "and userNo='1'";
		}else if(ad.getUser().equals("1") || ad.getUser().equals("2")){
			hql += "and userNo='"+ad.getUser()+"'";
		}else{
			hql += "and userNo='1'";
		}
		//		+ "and match.equipmentdetail.equipmentStorage.especification = '"+(ad.getVer()+"/"+ad.getModelCode())+"' ";
		if(ad.getDeviceType().equals("01")){//血压计
			hql += "and receive.match.equipmentdetail.equipmentStorage.equipment.kind.id = 1";
		}else if(ad.getDeviceType().equals("02")){//血糖仪
			hql += "and receive.match.equipmentdetail.equipmentStorage.equipment.kind.id = 2";
		}
//		System.out.println(hql);
		List<EquipmentLeader> leaders = receiveDao.findByHql(hql);
		if(leaders!=null && !leaders.isEmpty()){
			EquipmentLeader re = leaders.get(0);
			md.setLeader(re);
			md.setUpstr(ad.getDatastr());
			md.setCreateTime(new Date());
			//数据插入数据库
			if(receiveDao.add(md)){
				log.info("插入数据成功");
			}else{
				log.info("插入数据失败");
				return false;
			}
		}else{
			log.info("未找到设备领用信息");
			return false;
		}
		return true;
	}

}
